import React from 'react';

export default class TodoItem extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            editText: this.props.todo.text
        }
    }

    handleChange(event) {
        if (this.props.editing) {
            this.setState({
                editText: event.target.value});
        }
    }

    handleEdit(todo) {
        this.props.onEdit(todo);
        this.setState({editText: this.props.todo.text});
    }


    handleKeyDown(event) {
        if (event.which === 27) {
            this.setState({editText: this.props.todo.text});
            this.props.onCancel(event);
        } else if (event.which === 13) {
            let val = this.state.editText;
            if (val) {
                this.props.onSave(val);
                this.setState({editText: val});
            } else {
                this.props.onDestroy();
            }
        }
    }

//测试
//测试
//测试
//测试
//测试
    render() {
        let completed = this.props.todo.completed ? 'completed' : '';
        let editing = this.props.editing ? 'editing' : '';
        let className = completed +' '+editing;

        return (
            <li className={className}>
                <div className="view">
                    <input
                        className="toggle"
                        type="checkbox"
                        checked={this.props.todo.completed}
                        onChange={this.props.onToggle}
                    />
                    <label onDoubleClick={this.handleEdit.bind(this,this.props.todo)}>
                        {this.props.todo.text}
                    </label>
                    <button className="destroy" onClick={this.props.onDestroy} />
                </div>
                <input
                    ref="editField"
                    className="edit"
                    onKeyDown={this.handleKeyDown.bind(this)}
                    onChange={this.handleChange.bind(this)}
                    value={this.state.editText}
                />
            </li>
        );
    }
}